var URL = window.location.href.split(":");

var LOGIN_API = window.CONFIG.API + '/login';

var ajax = '';
var $_GET = getUrlInfo();

(function () {
  // 已登录直接跳转到登录成功
  if (localStorage.getItem('userId')) {
    window.parent.postMessage('logined', $_GET['url']);
  }
})();

// 登录接口
$(function () {
  $('body').keydown(function (e) {
    if (e.keyCode === 13) {
      login();
    }
  });

  $('#login-confirm').click(function () {
    login();
  });
});

function login() {
  if (ajax) {
    return false;
  } else {
    var username = $('input[name="username"]').val();
    var password = $('input[name="password"]').val();
    if (username.length <= 0) {
      showToast('请输入用户名');
      return false;
    }
    if (password.length <= 0) {
      showToast('请输入密码');
      return false;
    }

    ajax = $.ajax({
      url: LOGIN_API,
      type: 'post',
      data: {
        username: username,
        password: password
      },
      success: function (res) {
        if (res.success) {
          localStorage.setItem('userId', res.data);
          window.parent.postMessage('loginSuccess', $_GET['url']);
        } else {
          // 优化 可以将错误抛给iframe，优化错误提示
          if (res.msg) {
            console.log(res);
            showToast(res.msg);
            // window.parent.postMessage('loginError', $_GET['url']);
          } else {
            showToast('未知错误');
          }
        }
        ajax = '';
      },
      error: function (error) {
        console.log('登录错误', error);
        showToast('未知错误');
      }
    });
  }
}